package cn.iocoder.yudao.module.cmt.service.notify;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.notify.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.notify.CmtNotifyMessageDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.notify.CmtNotifyMessageMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class CmtNotifyMessageServiceImpl implements CmtNotifyMessageService {

    @Resource
    private CmtNotifyMessageMapper cmtNotifyMessageMapper;

    @Override
    public Long createMessage(CmtNotifyMessageSaveReqVO createReqVO) {
        CmtNotifyMessageDO message = BeanUtils.toBean(createReqVO, CmtNotifyMessageDO.class);
        cmtNotifyMessageMapper.insert(message);
        return message.getId();
    }

    @Override
    public void updateMessage(CmtNotifyMessageSaveReqVO updateReqVO) {
        validateMessageExists(updateReqVO.getId());
        CmtNotifyMessageDO updateObj = BeanUtils.toBean(updateReqVO, CmtNotifyMessageDO.class);
        cmtNotifyMessageMapper.updateById(updateObj);
    }

    @Override
    public void deleteMessage(Long id) {
        validateMessageExists(id);
        cmtNotifyMessageMapper.deleteById(id);
    }

    private void validateMessageExists(Long id) {
        if (cmtNotifyMessageMapper.selectById(id) == null) {
            throw exception(MESSAGE_NOT_EXISTS);
        }
    }

    @Override
    public CmtNotifyMessageDO getMessage(Long id) {
        return cmtNotifyMessageMapper.selectById(id);
    }

    @Override
    public PageResult<CmtNotifyMessageDO> getMessagePage(CmtNotifyMessagePageReqVO pageReqVO) {
        return cmtNotifyMessageMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMessageListByIds(List<Long> ids) {
        ids.forEach(this::validateMessageExists);
        cmtNotifyMessageMapper.deleteBatchIds(ids);
    }

}
